from flask import current_app, jsonify
from flask import g
from flask import request
from info import constants
from info import redis_store
from info.models import News, Category
from info.response_code import RET
from info.utils.commons import user_login_data
from . import index_blue
from flask import render_template


# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据
@index_blue.route('/newslist')
@user_login_data
def newslist():
    # 1.获取参数
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 2.参数类型转换
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 10

    # 3.分页查询
    try:
        # 判断编号是否不等于1
        filter_condition = ""
        if cid != "1":
            filter_condition = (News.category_id == cid)
        paginate = News.query.filter(filter_condition).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR, errmsg="获取新闻失败")

    # 4.获取分页属性,总页数,当前页,当前页对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 4.1对象列表转换为字典类型
    news_list = []
    for item in items:
        news_list.append(item.to_dict())
    # 5.数据拼接,返回响应
    return jsonify(erron=RET.OK, errmsg="请求成功", totalPage=totalPage, currentPage=currentPage, newsList=news_list)


@index_blue.route('/', methods=["GET", "POST"])
@user_login_data
def show_index():

    # 测试redis存取数据
    redis_store.set("name", "laowang")
    print(redis_store.get("name"))

    # 测试session存取数据
    # session["age"] = 18
    # print(session.get("age"))

    # 测试日志输出，来替代print输出
    # logging.debug("调试级别信息")
    # logging.info("详细级别信息")
    # logging.warning("警告级别信息")
    # logging.error("错误级别信息")

    # 当info文件中存在：
    # “为全局的日志工具对象（flask app使用的）添加日志记录器
    # logging.getLogger().addHandler(file_log_handler)”
    # 这俩句话的时候就可以使用current_app全局变量来打印程序日志
    # current_app.logger.debug("调试级别信息")
    # current_app.logger.info("详细级别信息")
    # current_app.logger.warning("警告级别信息")
    # current_app.logger.error("错误级别信息")

    # # 1.取出session中用户的编号
    # user_id = session.get("user_id")
    #
    # # 2.根据用户id取出用户对象
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 2.1查询热门新闻,前10条,按点击量查看
    try:
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻失败")

    # 2.2将对象列表转化为字典对象
    click_news_list = list()
    for item in news:
        click_news_list.append(item.to_dict())

    # 2.3 查询所有分类
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR, errmsg = "获取分类失败")

    # 2.4将分类列表转换成分类字典
    categories_list = list()
    for item in categories:
        categories_list.append(item.to_dict())

    # 3.携带用户数据,渲染页面
    data = {
        "user_info": g.user.to_dict() if g.user else "",
        "click_news_list": click_news_list,
        "categories": categories_list
    }
    return render_template("news/index.html", data=data)


# 处理网站logo
"""
所有网站都有logo,浏览器会自动发送一个get请求,地址是/favicon.ico
目的:获取服务器提供的logo图标
加载static中的额静态文件方法:
current_app.send_static_file("文件A"), 自动加载文件夹中的文件A,并生成一个响应体对象
"""


@index_blue.route('/favicon.ico')
def get_web_logo():
    return current_app.send_static_file("news/bitbug_facicon.ico")